package cn.hchaojie.blog.service;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import cn.hchaojie.blog.domain.AjaxResponse;
import cn.hchaojie.blog.domain.Post;
import cn.hchaojie.blog.mapper.PostMapper;
import cn.hchaojie.blog.utils.SessionFactoryUtils;

public class PostService {
	PostMapper mapper = null;
	
	public List<Post> findAll() {
		SqlSessionFactory factory = SessionFactoryUtils.getFactory();
		SqlSession session = factory.openSession();
		mapper = session.getMapper(PostMapper.class);
		
		List<Post> all = mapper.findAll();
		
		session.close();
		
		return all;
	}
	
	/**
	 * 
	 * @param page - 第几页，从1开始
	 * @param size
	 * @return
	 */
	public AjaxResponse<Post> findPage(int page, int size) {
//		SqlSessionFactory factory = SessionFactoryUtils.getFactory();
//		SqlSession session = factory.openSession();
//		mapper = session.getMapper(PostMapper.class);
//		
		// 当前页数据
		List<Post> all = mapper.findPage((page - 1) * size, size);

		// 一共有多少条数据
		int count =  mapper.findCount();

		AjaxResponse<Post> result = new AjaxResponse<>();
		result.setData(all);
		result.setCount(count);
		
//		session.close();
		
		return result;
	}
}
